<template>
    <div class="avatarUpload">
      <div class="avatar-info-box">
        <el-button type="text" @click="dialogVisible = true" class="">
          <div class="avatar-info-pic"></div>
          <p>点击头像更换</p>
        </el-button>
      </div>

      <el-dialog title="提示" v-model="dialogVisible" size="tiny">
        <!-- avatar pic upload -->
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :on-success="handleAvatarScucess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <!-- upload end  -->
        <!-- 文件上传确定之后 提示正在上传 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>
<style>
  .avatarUpload{
    margin-bottom: 10px;
    background: #EFF2F7;
  }
  .avatar-info-box{
    padding: 15px;
    text-align: center;
    border-bottom: 1px solid #EEE;
  }
  .avatar-info-pic{
    height: 150px;
    width: 150px;
    border: 1px solid #CCC;
    border-radius: 50%;
    background: url(./avatarBg.jpg) no-repeat;
  }

  .avatar-uploader {
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .el-icon-plus:before {
    position: absolute;
    top: 70px;
    left: 75px;
  }
</style>
<script>

    export default{
        name : 'avatarUpload',
        data(){
            return{
                dialogVisible: false,
                imageUrl: ''
            }
        },
        components:{

        },
        methods: {
          handleAvatarScucess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
          },
          beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
              this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
              this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
          }
        }
    }
</script>
